﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Server.Helper
{
    public class WindowHelper
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("User32.dll")]
        public static extern IntPtr WindowFromPoint(Point p);


        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);


        [DllImport("user32.dll")]
        public static extern IntPtr GetDC(IntPtr hWnd);

        // P/Invoke to release the device context
        [DllImport("user32.dll")]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        // P/Invoke to get the color of a pixel at a specific coordinate
        [DllImport("gdi32.dll")]//取指定点颜色 
        public static extern int GetPixel(IntPtr hdc, Point p);


        public static Point GetWindowTopLeftCorner(string processName, string windowTitle)
        {
            IntPtr hWnd = FindWindow(null, windowTitle);
            if (hWnd == IntPtr.Zero)
            {
                hWnd = FindWindow(null, getAnotherTitle(windowTitle));
                if (hWnd == IntPtr.Zero)
                {
                    return Point.Empty; // Window not found
                }
            }

            // Check if window belongs to the specified process
            uint processId;
            ProcessInfoHelper.GetWindowThreadProcessId(hWnd, out processId);
            var process = System.Diagnostics.Process.GetProcessById((int)processId);
            if (!process.ProcessName.Contains(processName))
            {
                return Point.Empty; // Window found, but belongs to a different process
            }

            RECT rect;
            if (!GetWindowRect(hWnd, out rect))
            {
                return Point.Empty; // Failed to get window rect
            }

            return new Point(rect.Left, rect.Top);
        }


        public static string getAnotherTitle(string windowTitle)
        {
            switch (windowTitle)
            {
                case "钟长明":
                    return "钟长明(zhcm)";
                case "谷苏":
                    return "谷苏(gusu)";
                case "王旭":
                    return "王旭(wangxu)";
                case "赵凯特":
                    return "赵凯特(zhaokaite)";
                default:
                    return windowTitle;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    }
}
